import ctypes
import sys
import json
from ctypes import wintypes
import win32gui
import win32con

# Win32 API 定义
user32 = ctypes.windll.user32
GetWindowTextW = user32.GetWindowTextW
GetWindowTextLengthW = user32.GetWindowTextLengthW
IsWindowVisible = user32.IsWindowVisible
EnumWindows = user32.EnumWindows
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)

# 窗口句柄缓存
_hwnd_cache = {}

def _pick_main_hwnd_by_title(keyword: str):
    key = keyword.lower().strip()
    if not key:
        return None

    if key in _hwnd_cache:
        hwnd = _hwnd_cache[key]
        if IsWindowVisible(hwnd):
            return hwnd
        _hwnd_cache.pop(key, None)

    hwnds = []
    def callback(hwnd, _):
        if IsWindowVisible(hwnd):
            length = GetWindowTextLengthW(hwnd)
            if length > 0:
                buf = ctypes.create_unicode_buffer(length + 1)
                GetWindowTextW(hwnd, buf, length + 1)
                if key in buf.value.lower():
                    hwnds.append(hwnd)
        return True

    EnumWindows(EnumWindowsProc(callback), 0)
    return hwnds[0] if hwnds else None

def _get_screen_work_area(hwnd):
    class MONITORINFO(ctypes.Structure):
        _fields_ = [
            ("cbSize", wintypes.DWORD),
            ("rcMonitor", wintypes.RECT),
            ("rcWork", wintypes.RECT),
            ("dwFlags", wintypes.DWORD)
        ]

    hmon = user32.MonitorFromWindow(hwnd, win32con.MONITOR_DEFAULTTONEAREST)
    if not hmon:
        return (0, 0, 1920, 1080)

    mi = MONITORINFO()
    mi.cbSize = ctypes.sizeof(MONITORINFO)
    user32.GetMonitorInfoW(hmon, ctypes.byref(mi))
    work_area = mi.rcWork
    return (
        work_area.left,
        work_area.top,
        work_area.right - work_area.left,
        work_area.bottom - work_area.top
    )

def fit_window_left_top_uia(windowName: str = "BOSS直聘", windowSize: float = 0.7) -> bool:
    try:
        user32.SetProcessDPIAware()
    except Exception as e:
        print(f"DPI感知失败: {e}", file=sys.stderr)

    try:
        ratio = float(windowSize)
    except Exception as e:
        print(f"windowSize转换失败: {e}", file=sys.stderr)
        ratio = 0.7
    ratio = max(0.0, min(1.0, ratio))

    hwnd = _pick_main_hwnd_by_title(windowName)
    if not hwnd:
        print(f"未找到窗口: {windowName}", file=sys.stderr)
        return False

    try:
        # 修复：正确设置窗口状态（移除错误的SetWindowPlacement调用，改用ShowWindow确保恢复正常状态）
        win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)  # 恢复窗口（非最大化/最小化）
        # 等待窗口状态更新
        ctypes.windll.kernel32.Sleep(100)  # 更可靠的休眠
        win32gui.SetForegroundWindow(hwnd)  # 激活窗口到前台
        # 获取工作区信息
        work_left, work_top, work_width, work_height = _get_screen_work_area(hwnd)
        print(f"工作区尺寸: 宽={work_width}, 高={work_height}", file=sys.stderr)

        # 计算目标尺寸
        target_width = int(work_width * ratio)
        target_height = work_height
        print(f"目标尺寸: 宽={target_width}, 高={target_height}", file=sys.stderr)

        # 调整窗口位置和尺寸
        win32gui.SetWindowPos(
            hwnd,
            win32con.HWND_NOTOPMOST,
            work_left, work_top,
            target_width, target_height,
            win32con.SWP_NOZORDER | win32con.SWP_SHOWWINDOW
        )
        return True

    except Exception as e:
        print(f"窗口调整失败: {e}", file=sys.stderr)
        return False

# 执行示例
# if __name__ == "__main__":
#     ctx = {"windowName": "BOSS直聘", "windowSize": "0.7"}
#     print('开始执行窗口操作', file=sys.stderr)
#     results = fit_window_left_top_uia(ctx.get('windowName'), ctx.get('windowSize'))
#     print('窗口操作结果', results, file=sys.stderr)
#     print(json.dumps({"results": results}, ensure_ascii=False), flush=True)